package se.webbzon.oschi01.region;

import java.awt.Point;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import se.webbzon.oschi01.singleton.Singleton;
import se.webbzon.oschi01.utils.Reader;
import se.webbzon.oschi01.world.DefaultRegion;
import se.webbzon.oschi01.world.Region;

public class RegionReader implements Singleton, Reader<Region,RegionReference> {
	
	private final int entries = 1024;
	
	private RegionReader() {};
	
	public URLRegion read(RegionReference reference) throws IOException {
		int[] locations = null, timestamps = null;
		URL url = reference.getUrl();
		try (InputStream is = url.openStream()) {
			DataInputStream dis = new DataInputStream(is);
			locations = new int[entries];
			timestamps = new int[entries];
			for (int i = 0; i < entries; i++) {
				locations[i] = dis.readInt();
			}
			for (int i = 0; i < entries; i++) {
				timestamps[i] = dis.readInt();
			}
		} catch (IOException e) {
			throw e;
		}
		
		int xs = reference.getX();
		int zs = reference.getZ();
		Region region = new DefaultRegion(xs,zs);
		for (int i = 0; i < entries; i++) {
			final int location = locations[i];
			if (location != 0) {
				Point coordiantes = new Point(32 * xs + (i % 32), 32 * zs + (i / 32));
				int offset = location >>> 8;
				byte sectorCount = (byte) location;
				region.addChunk(new URLChunk(url,offset,sectorCount,timestamps[i],coordiantes));
			}
		}
		return new URLRegion(reference.getUrl(),region);
	}

}
